import constants as con
import pymunk 
import pygame
from pygame.color import *
from pymunk import Vec2d
from math import fabs

import xzgoal

class Player(pygame.sprite.Sprite):
    image = None

    def __init__(self,parent):
        pygame.sprite.Sprite.__init__(self)

        if Player.image is None:
            Player.image = con.load_image('dat_dad.png')

        self.width = int(con.window_size[0] * 0.0625)
        self.height = int(con.window_size[1] * 0.084)

        self.image = pygame.transform.scale(Player.image, (self.width,self.height))
        self.parent = parent

        self.defX = int(con.window_size[0] / 2)
        self.defY = int((con.window_size[1] / 2) * 0.75)
        
        self.friction = 0.1
        self.mass = 0.00001
        self.moment = pymunk.inf
        self.radius = 10

        self.movement = 0
        self.target_movement = 0
        self.move_factor = 1

        self.body = pymunk.Body(self.mass,self.moment)        
        self.body.position = (self.defX,self.defY)
        self.body.velocity_func = self.playerUpdateVelocity

        self.shape = pymunk.Circle(self.body, self.radius, (0,0))
        self.shape.layers = 1
        self.type = 'player'

        self.rect = pygame.Rect(self.body.position.x,self.body.position.y,self.width,self.height)

        self._layer = 1

        self.parent.space.add(self.body,self.shape)
        self.parent.sprites.add(self)

    def playerUpdateVelocity(self,body,gravity,damping,dt):
        body.update_velocity(body,gravity,damping,dt)
        self.movement = self.target_movement
        body.velocity = (self.movement,body.velocity[1])

    def update(self):

        if self.body.position.y < 0:
            self.parent.goals.append( xzgoal.Goal( self.parent, "YOU FELL OFF!!", 2))
            self.body.position = (self.defX, self.defY)

        self.rect.centerx = self.body.position.x 
        self.rect.bottom = con.flipy(self.body.position.y - self.radius)

    def pymunkDraw(self,screen):
        p = con.to_pygame(self.body.position)
        pygame.draw.circle(screen, THECOLORS["orange"], p, int(self.radius), 2)

    def moveLeft(self):
        self.target_movement = -100

    def moveRight(self):
        self.target_movement = 100

    def moveStop(self):
        self.target_movement = 0

    def chaseMouse(self,game):

        p = pygame.mouse.get_pos()

        #if Vec2d.get_distance(self.body.position, (p[0],con.flipy(p[1]))) < 30:
        if fabs(p[0] - self.body.position[0]) <= 30:
            self.target_movement = 0
        elif p[0] < self.body.position[0]:
            self.target_movement = -120
        elif p[0] > self.body.position[0]:
            self.target_movement = 120


